import { defineStore } from "pinia";
import { computed, reactive, ref } from "vue";

import { setToken } from "@/utils/auth.ts";

import {
  loginApi,
  sendEmailCodeApi,
  registerApi,
  emailVerifyCodeApi,
  forgotPasswordApi,
} from "@/api/login.ts";

export interface Userinfo {
  id: string;
  username: string;
  password?: string;
  email: string;
  code: string;
  phone: string;
  address: string;
  birthDate?: number;
  lastLoginTime?: number;
  role: number;
}

export const useUserStore = defineStore("user", () => {
  //state
  const userinfo = reactive<Userinfo>({
    id: "",
    username: "admin",
    password: "123456",
    email: "",
    code: "",
    phone: "",
    address: "",
    birthDate: 0,
    lastLoginTime: 0,
    role: 0,
  });
  const isLogined = ref<boolean>(false);

  //getters
  const getUserinfo = computed(() => userinfo);

  //action
  const login = async (params): Promise<boolean> => {
    if (params.loginType === "account") {
      if (
        params.username === userinfo.username &&
        params.password === userinfo.password
      ) {
        isLogined.value = true;
        userinfo.id = "1"; // 模拟用户ID
        userinfo.lastLoginTime = Date.now(); // 更新最后登录时间
        return true;
      } else {
        return false; // 登录失败
      }
    } else {
      // loginApi
      // 1账户注册，3是密码找回
      let result = await loginApi({
        email: params.email,
        password: params.password,
      });

      if (result.data) {
        setToken(result.data.token);

        localStorage.setItem(
          "userInfo",
          JSON.stringify({
            ...result.data,
            token: null,
          })
        );
      }
    }
  };
  const logout = (fn): void => {
    console.log("logout");
    fn && fn();
  };

  // 邮箱验证
  const emailVerifyCode = async (params: {
    email: string;
    sendType: number | string; // 1账户注册，3是密码找回
    verificationCode: string;
  }) => {
    let result = (await emailVerifyCodeApi(params)) as any;
    if (result.data == "1") {
      return result;
    } else {
      // 验证失败
      return Promise.reject(new Error(result.message || "邮箱验证失败"));
    }
  };

  // 发送邮件
  const sendEmailCode = async (params: {
    email: string;
    sendType: number | string; // 1账户注册，3是密码找回
  }) => {
    // 1账户注册，3是密码找回
    let result = await sendEmailCodeApi(params);
    return result;
  };

  // 注册
  const register = async (params: {
    username: string;
    password: string;
    email: string;
    telephone?: string;
  }) => {
    // 1账户注册，3是密码找回
    let result = await registerApi(params);

    return result;
  };

  // 忘记密码
  const forgotPassword = async (params: {
    password: string;
    email: string;
    code: string;
  }) => {
    // 1账户注册，3是密码找回
    let result = await forgotPasswordApi(params);
    return result;
  };

  const getTest = async () => {
    return 1;
  };

  return {
    userinfo,
    isLogined,
    getUserinfo,
    login,
    logout,
    forgotPassword,

    emailVerifyCode,
    sendEmailCode,
    register,
    getTest,
  };
});
// 这里定义了一个用户信息的 Pinia store，包含用户信息、登录状态以及登录和登出方法。
